package cn.edu.lingnan.config;

import cn.edu.lingnan.utils.ConnectionCounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

/**
 * WebSocket 事件监听器，用于统计连接数。
 */
@Component
public class WebSocketEventListener {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);

    @Autowired
    private ConnectionCounter connectionCounter;

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectEvent event) {
        connectionCounter.increment();
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        String user = accessor.getUser() != null ? accessor.getUser().getName() : "Anonymous";
        logger.info("新的连接建立: 用户 = {}, 当前连接数 = {}", user, connectionCounter.getActiveConnections());
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        connectionCounter.decrement();
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        String user = accessor.getUser() != null ? accessor.getUser().getName() : "Anonymous";
        logger.info("连接断开: 用户 = {}, 当前连接数 = {}", user, connectionCounter.getActiveConnections());
    }
}
